<template>
	<div class="system-menu-container layout-pd">
		<el-card shadow="hover">
			<div class="system-menu-search mb15">
				<el-row :gutter="20">
					<el-col :span="24" v-auth="'monitor:logininfor:query'" class="col-center">
						<el-input size="default" placeholder="登录地址" v-model="state.param.ipaddr" class="mt10" />
						<el-input size="default" placeholder="用户名称" v-model="state.param.userName" class="mt10" />
						<el-select v-model="state.param.status" placeholder="登录状态" clearable size="default" class="mt10">
							<el-option v-for="dict in sys_common_status" :key="dict.value" :label="dict.label"
								:value="dict.value" />
						</el-select>
						<el-date-picker v-model="state.dateRange" type="daterange" range-separator="至"
							start-placeholder="开始时间" end-placeholder="结束时间" size="default" class="mt10"
							style="max-width: 250px;" />
						<el-button size="default" type="primary" :icon="'ele-Search'" class="mt10" @click="getTableData">
							查询
						</el-button>
						<el-button size="default" class="mt10" type="info" @click="resetParamData()">
							重置
						</el-button>
					</el-col>
					<el-col :span="24"
						v-auths="['monitor:logininfor:remove', 'monitor:logininfor:export', 'monitor:logininfor:unlock']">
						<el-button size="default" type="danger" class="mt10" @click="handleBatchDel()" :icon="'ele-Delete'"
							v-auth="'monitor:logininfor:remove'">
							删除
						</el-button>
						<el-button size="default" type="danger" class="mt10" @click="onBatchDelOperlog()"
							:icon="'ele-Delete'" v-auth="'monitor:logininfor:remove'">
							清空
						</el-button>
						<el-button size="default" type="success" class="mt10" @click="handleUnlock()" :icon="'ele-Unlock'"
							v-auth="'monitor:logininfor:unlock'">
							解锁
						</el-button>
						<el-button size="default" type="warning" class="mt10" @click="onExportLogingfo()"
							:icon="'ele-Download'" v-auth="'monitor:logininfor:export'">
							导出
						</el-button>
					</el-col>
				</el-row>
			</div>
			<el-table :data="state.tableData.data" v-loading="state.tableData.loading" style="width: 100%"
				ref="multipleTableRef" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="访问编号" width="95" prop="infoId" show-overflow-tooltip />
				<el-table-column label="用户名称" width="95" prop="userName" show-overflow-tooltip sortable="custom"
					:sort-orders="['descending', 'ascending']" />
				<el-table-column label="地址" align="center" prop="ipaddr" show-overflow-tooltip />
				<el-table-column label="登录地点" align="center" prop="loginLocation" show-overflow-tooltip />
				<el-table-column label="操作系统" align="center" prop="os" show-overflow-tooltip />
				<el-table-column label="浏览器" align="center" prop="browser" show-overflow-tooltip />
				<el-table-column label="登录状态" width="95" prop="status">
					<template #default="scope">
						<dict-tag :options="sys_common_status" :value="scope.row.status" />
					</template>
				</el-table-column>
				<el-table-column label="描述" align="center" prop="msg" show-overflow-tooltip />
				<el-table-column label="访问时间" align="center" prop="loginTime" sortable="custom"
					:sort-orders="['descending', 'ascending']" width="180">
					<template #default="scope">
						<span>{{ scope.row.loginTime }}</span>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange"
				class="mt15 paginationFlex" style="justify-content: flex-end;" :pager-count="5" :page-sizes="[10, 20, 30]"
				v-model:current-page="state.param.pageNum" background v-model:page-size="state.param.pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="state.total">
			</el-pagination>
		</el-card>

	</div>
</template>

<script setup lang="ts" name="systemOperlog">
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox, ElMessage, dayjs, ElTable } from 'element-plus';
import { useLogininforApi } from '/@/api/monitor/logininfor';
import { useDict } from '/@/utils/dict';
import { download } from '/@/utils/tool';
// 引入组件

const { sys_common_status } = useDict("sys_common_status");

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<RowLogininforType[]>([])

const state = reactive<TableType>({
	tableData: {
		data: [],
		operlogOptions: [],
	},
	total: 0,
	loading: false,
	dateRange: [], // 时间范围
	param: {
		pageNum: 1,
		pageSize: 10,
		ipaddr: undefined,
		userName: undefined,
		status: undefined,
		orderByColumn: undefined,
		isAsc: undefined
	},
});

/**
 * 初始化表格数据
 * @returns
 */
const getTableData = async () => {
	state.tableData.loading = true;
	try {
		let param = {};
		if (state.dateRange && state.dateRange.length > 0) {
			param = {
				...state.param,
				'params[beginTime]': dayjs(state.dateRange[0]).format('YYYY-MM-DD'),
				'params[endTime]': dayjs(state.dateRange[1]).format('YYYY-MM-DD')
			};
		} else {
			param = { ...state.param };
		}
		const res = await useLogininforApi().list({
			...param,
		});
		state.tableData.data = res.rows;
		state.total = res.total;
	} catch (error) {
		Promise.reject(error);
	}
	state.tableData.loading = false;
};

/**
 * 多选
 */
const handleSelectionChange = (val: RowLogininforType[]) => {
	multipleSelection.value = val
}

/**
 * 导出登录日志
 */
const onExportLogingfo = () => {
	download("monitor/logininfor/export", {
		...state.param,
	}, `config_${new Date().getTime()}.xlsx`);
};


/**
 * 批量解锁
 */
const handleUnlock = async () => {
	const confirmResult = await ElMessageBox.confirm('此操作将解锁用户, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
	if (confirmResult !== 'confirm') {
		return
	}
	const deletePromises = multipleSelection.value.map((item) => {
		return useLogininforApi().unlockLogininfor(item.infoId)
	})
	try {
		const results = await Promise.all(deletePromises)
		results.forEach((res) => {
			if (res.code === 200) {
				ElMessage.success(res.msg)
			} else {
				ElMessage.error(res.msg)
			}
		})
		getTableData()
	} catch (err) {
		return Promise.reject(err)
	}
}

/**
 * 批量删除日志
 */
const handleBatchDel = async () => {
	const confirmResult = await ElMessageBox.confirm('此操作将删除选中的登录日志, 是否继续?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	})
	if (confirmResult !== 'confirm') {
		return
	}
	const deletePromises = multipleSelection.value.map((item) => {
		return useLogininforApi().delLogininfor(item.infoId)
	})
	try {
		const results = await Promise.all(deletePromises)
		results.forEach((res) => {
			if (res.code === 200) {
				ElMessage.success(res.msg)
			} else {
				ElMessage.error(res.msg)
			}
		})
		getTableData()
	} catch (err) {
		return Promise.reject(err)
	}
}




/**
 * 清空登录日志
 */
const onBatchDelOperlog = async () => {
	try {
		await ElMessageBox.confirm(`此操作将清空登录日志, 是否继续?`, '提示', {
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
		}).then(() => {
			useLogininforApi().cleanLogininfor().then((res) => {
				if (res.code === 200) {
					ElMessage.success(res.msg);
					getTableData();
				} else {
					ElMessage.error(res.msg);
				}
			});
		});
	} catch (error) {
		Promise.reject(error);
	}
};

/**
 * 重置查询登录日志
 */
const resetParamData = () => {
	state.dateRange = [];
	state.param = {
		pageNum: 1,
		pageSize: 10,
		operlogName: '',
		status: '',
	};
	getTableData();
};


// 分页改变
const onHandleSizeChange = (val: number) => {
	state.param.pageSize = val;
	getTableData();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.param.pageNum = val;
	getTableData();
};
// 页面加载时
onMounted(() => {
	getTableData();
});

</script>
<style lang="scss" scoped>
.mt10 {
	max-width: 140px;
	margin: 10px 0 10px 10px;
}
</style>